package com.caine.web.service.impl;

import com.caine.web.mapper.TestMapper;
import com.caine.web.service.ITestService01;
import com.caine.web.service.ITestService02;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author CaineZhu
 * @since 2020-11-20
 */
@Service
@Transactional
public class TestServiceImpl01 implements ITestService01 {

    Logger logger = LoggerFactory.getLogger(TestServiceImpl01.class);

    @Autowired
    private ITestService02 testService02;
    @Resource
    private TestMapper testMapper;

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    @Override
    public void lock01() {
        testMapper.updateById(1L);
        waiting("lock01->updateById 1L", 5L);
        testMapper.updateById(2L);
        waiting("lock01->updateById 2L", 5L);
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    @Override
    public void lock02() {
        testMapper.updateById(2L);
        waiting("lock01->updateById 2L", 5L);
        testMapper.updateById(1L);
        waiting("lock01->updateById 1L", 5L);
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    @Override
    public void nolock() {
        testService02.updateById02(2L);
        waiting("nolock->updateById02 2L", 5L);
        testService02.updateById02(1L);
        waiting("nolock->updateById02 1L", 5L);
    }

    private void waiting(String name, long time) {
        logger.info("{} sleep for {} second.", name, time);
        try {
            TimeUnit.SECONDS.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
